package com.guigu.qingcheng.orderservice.service.impl;

import com.guigu.qingcheng.orderservice.service.CartSerivce;
import com.guigu.qingcheng.orderservice.service.CategoryFeign;
import com.guigu.qingcheng.orderservice.service.TbPreferentialService;
import com.guigu.qingcheng.pojo.goods.TbCategory;
import com.guigu.qingcheng.pojo.goods.TbSku;
import com.guigu.qingcheng.pojo.order.TbOrderItem;
import com.guigu.qingcheng.utils.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartSerivce {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CategoryFeign categoryFeign;
    @Autowired
    private TbPreferentialService service;


    @Override
    public List<Map<String, Object>> findCartList(String username) {
        List<Map<String, Object>> cartList = (List<Map<String, Object>>)
                redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);
        if (cartList == null) {
            cartList = new ArrayList<>();
        }
        return cartList;
    }

    @Override
    public void addItem(String username, String skuId, Integer num) {
        //实现思路： 遍历购物车，如果购物车中存在该商品则累加数量，如果不存在则添加购物车项
        //获取购物车
        List<Map<String, Object>> cartList = findCartList(username);
        boolean flag=false;//是否在购物车中存在
        for( Map map:cartList ){
            TbOrderItem orderItem= (TbOrderItem)map.get("item");
            if(orderItem.getSkuId().equals(skuId)){ //购物车存在该商品
                if(orderItem.getNum()<=0){ //如果数量小于等于0
                    cartList.remove(map);//购物车项删除
                    break;
                }
                int weight = orderItem.getWeight() / orderItem.getNum();//单个商品重量
                orderItem.setNum( orderItem.getNum()+num ); //数量累加
                orderItem.setMoney(orderItem.getNum()*orderItem.getPrice() );//金额计算
                orderItem.setWeight( weight*orderItem.getNum() );//重量计算
                if(orderItem.getNum()<=0){ //如果数量小于等于0
                    cartList.remove(map);//购物车项删除
                }
                flag=true;
                break;
            }
        }
        //如果购物车中没有该商品，则添加
        if(flag==false){
            TbSku sku = categoryFeign.findByIds(skuId);
            if(sku==null){
                throw new RuntimeException("商品不存在");
            }
            if(!"1".equals(sku.getStatus())){
                throw new RuntimeException("商品状态不合法");
            }
            if(num<=0){ //数量不能为0或负数
                throw new RuntimeException("商品数量不合法");
            }
            TbOrderItem orderItem=new TbOrderItem();
            orderItem.setSkuId(skuId);
            orderItem.setSpuId(sku.getSpuId());
            orderItem.setNum(num);
            orderItem.setImage(sku.getImage());
            orderItem.setPrice(sku.getPrice());
            orderItem.setName(sku.getName());
            orderItem.setMoney( orderItem.getPrice()*num );//金额计算
            if(sku.getWeight()==null){
                sku.setWeight(0);
            }
            orderItem.setWeight(sku.getWeight()*num); //重量计算
//商品分类
            orderItem.setCategoryId3(sku.getCategoryId());
            TbCategory category3 =
                    (TbCategory)redisTemplate.boundHashOps(CacheKey.CATEGORY).get(sku.getCategoryId());
            if(category3==null){
                category3 =
                        categoryFeign.findById2(sku.getCategoryId()); //根据3级分类id查2级
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(sku.getCategoryId(),
                        category3 );
            }
            orderItem.setCategoryId2(category3.getParentId());
            TbCategory category2 =
                    (TbCategory)redisTemplate.boundHashOps(CacheKey.CATEGORY).get(category3.getParentId());
            if(category2==null ){
                category2 =
                        categoryFeign.findById2(category3.getParentId()); //根据2级分类id查询1级
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(category3.getParentId()
                        , category2 );
            }
            orderItem.setCategoryId1(category2.getParentId());
            Map map=new HashMap();
            map.put("item",orderItem);
            map.put("checked",true);//默认选中
            cartList.add(map);
        }
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
    }

    @Override
    public boolean updateChecked(String username, String skuId, boolean checked) {
        //获取购物车
        List<Map<String,Object>> cartList= findCartList(username);
        //判断缓存中是含有已购物商品
        boolean isOk=false;
        for (Map map:cartList) {
            TbOrderItem orderItem=(TbOrderItem)map.get("item");
            if(orderItem.getSkuId().equals(skuId)){
                map.put("checked",checked);
                isOk=true;//执行成功
                break;
            }
        }
            if(isOk){
            redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);//
        }
        return isOk;
    }

    @Override
    public void deleteCheckedCart(String username) {
        //获取未选中的购物车
        List<Map<String,Object>> cartList= findCartList(username).stream().
                filter(cart -> (boolean)cart.get("checked") == false).
                collect(Collectors.toList());
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
    }

    @Override
    public int preferential(String username) {
        //获取选中的购物车 List<OrderItem> List<Map>
        List<TbOrderItem> items = findCartList(username).stream().
                filter(cart -> (boolean) cart.get("checked") == true).
                map(cart -> (TbOrderItem) cart.get("item")).collect(Collectors.toList());
        //按分类聚合统计每个分类的金额 group by
        Map<Integer, IntSummaryStatistics> cartMap = items.stream().
                collect(Collectors.groupingBy(TbOrderItem::getCategoryId3, Collectors.summarizingInt(TbOrderItem::getMoney)));
        //循环结果，统计每个分类的优惠金额，并累加
        int allPreMoney = 0;//累积优惠金额
        for (Integer categoryId : cartMap.keySet()) {
            //获取品类的消费金额
            int money = (int) cartMap.get(categoryId).getSum();
            //获取优惠金额
            int preMoney = service.findPreMoneyByCategoryId(categoryId, money);
            System.out.println("分类：" + categoryId + " 消费金额：" + money + " 优惠金额：" + preMoney);
            allPreMoney += preMoney;
        }
        return allPreMoney;
    }

    @Override
    public List<Map<String, Object>> findNewOrderItemList(String username) {
        //获取选中的购物车
        List<Map<String, Object>> list = findCartList(username);
        //循环购物车列表，重新读取每个商品的最新价格
        for (Map<String, Object> cart: list) {
            TbOrderItem orderItem = (TbOrderItem) cart.get("item");
            TbSku  sku= categoryFeign.findByIds(orderItem.getSkuId());
            orderItem.setPrice(sku.getPrice());
            //更新金额
            orderItem.setMoney(sku.getPrice()*orderItem.getNum());
        }
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,list);
        return list;
    }
}
